/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-13 23:44:25
 * @Last modified by:   ls-mac
 * @Last modified time: 2019-10-14 15:00:15
 */

import { dictStorePage, dictStoreAddOrEdit, dictStoreDetail, dictStoreDelete } from 'services/dict';

export default {
  namespace: 'storeList',
  state: {
    data: {
      list: [],
      pagination: {},
    },
    dictStoreDetail: {},
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(dictStorePage, payload);
      yield put({
        type: 'saveList',
        payload: response,
      });
    },
    *dictStoreAddOrEdit({ payload, callback }, { call, put }) {
      const response = yield call(dictStoreAddOrEdit, payload);
      if (callback) callback(response);
    },
    *dictStoreDetail({ payload, callback }, { call, put }) {
      const response = yield call(dictStoreDetail, payload);
      yield put({
        type: 'saveDictStoreDetail',
        payload: response,
      });
    },
    *dictStoreDelete({ payload, callback }, { call, put }) {
      const response = yield call(dictStoreDelete, payload);
      if (callback) callback(response);
    },
  },

  reducers: {
    saveList(state, action) {
      const {
        data: { storeList, pageIndex, pageSize, recordCount },
      } = action.payload;

      const newList = storeList.map(val => {
        const v = val;
        v.key = `k${v.id}`;
        return v;
      });
      return {
        ...state,
        data: {
          list: newList,
          pagination: {
            current: pageIndex,
            total: recordCount,
            pageSize,
          },
        },
      };
    },

    saveDictStoreDetail(state, action) {
      const { data } = action.payload;
      return {
        ...state,
        dictStoreDetail: data,
      };
    },
  },
};
